package view.MainWindow.Conponents;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class testtable extends JFrame {

    public testtable() {
        // 设置窗口基本属性
        setTitle("CustomTableFactory 测试");
        setSize(700, 400);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null); // 居中显示

        // 定义表头
        String[] columnTitles = {"姓名", "年龄", "操作"};

        // 使用工厂创建表格组件
        JPanel tablePanel = new CustomTableFactory(columnTitles, 5) // 5 行初始数据
                .setPanelAt(2) // 第三列是 Panel 类型（操作列）
                .setRowHeight(30)
                .build();

        // 获取 JTable 对象以便填充数据
        JTable table = getJTableFromPanel(tablePanel);

        // 填充数据
        DefaultTableModel model = (DefaultTableModel) table.getModel();
        model.setValueAt("张三", 0, 0);
        model.setValueAt("28", 0, 1);
        model.setValueAt(createButtonPanel("详情"), 0, 2);

        model.setValueAt("李四", 1, 0);
        model.setValueAt("32", 1, 1);
        model.setValueAt(createButtonPanel("删除"), 1, 2);

        model.setValueAt("王五", 2, 0);
        model.setValueAt("25", 2, 1);
        model.setValueAt(createButtonPanel("修改"), 2, 2);

        model.setValueAt("赵六", 3, 0);
        model.setValueAt("30", 3, 1);
        model.setValueAt(createButtonPanel("查看"), 3, 2);

        model.setValueAt("孙七", 4, 0);
        model.setValueAt("22", 4, 1);
        model.setValueAt(createButtonPanel("编辑"), 4, 2);

        // 添加表格到窗口
        add(tablePanel, BorderLayout.CENTER);

        // 显示窗口
        setVisible(true);
    }

    // 从 JPanel 中获取 JTable（因为我们封装在 JScrollPane 中）
    private JTable getJTableFromPanel(JPanel panel) {
        JScrollPane scrollPane = (JScrollPane) panel.getComponent(0);
        return (JTable) scrollPane.getViewport().getView();
    }

    // 创建一个包含按钮的 Panel
    private JPanel createButtonPanel(String buttonText) {
        JButton button = new JButton(buttonText);
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(testtable.this,
                        "你点击了按钮: " + buttonText);
            }
        });

        JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 0));
        panel.add(button);
        return panel;
    }

    // 主方法，启动程序
    public static void main(String[] args) {
        // 在事件调度线程中运行 GUI
        SwingUtilities.invokeLater(() -> new testtable());
    }
}